package tools;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.oreilly.servlet.MultipartRequest;

public class Upload {
public static MultipartRequest upload(HttpServletRequest request,String saveDirectory,int maxPostSize,String encode) throws IOException{
	MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,encode);
	return multi;
}

public static String getFileName(MultipartRequest multi,String saveDirectory) {
	Enumeration files = multi.getFileNames();
	String lastFileName=null;
	     while (files.hasMoreElements()) {
	       String name = (String)files.nextElement();
	       File f = multi.getFile(name);
	       lastFileName=getFileNameUniq(multi, saveDirectory, name, f);
	     }
	    
	     return lastFileName;
}


private static String getFileNameUniq(MultipartRequest multi, String saveDirectory, String name, File f) {
	String lastFileName=null;
	long time=System.currentTimeMillis();
	   if(f!=null){
	     String fileName = multi.getFilesystemName(name);
	     f.renameTo(new File(saveDirectory+"\\"+time+"$"+fileName));
	      lastFileName=time+"$"+fileName;
	      }
	   return lastFileName;
}

public static String getFileNames(MultipartRequest multi, String saveDirectory) {
StringBuilder sb=new StringBuilder();
	Enumeration files = multi.getFileNames();

	     while (files.hasMoreElements()) {
	       String name = (String)files.nextElement();
	       File f = multi.getFile(name);
	       long time=System.currentTimeMillis();
	       if(f!=null){
	    	   String fileName = multi.getFilesystemName(name);
	  	       f.renameTo(new File(saveDirectory+"\\"+time+"$"+fileName));
	  	      String lastFileName = time+"$"+fileName;
	  	      sb.append(lastFileName).append(",");
	  	     }
	     }
	    
	     if(sb.toString()!=null&&sb.length()>1){
	    	 sb= sb.deleteCharAt(sb.length()-1);
	    	return sb.toString();
	     }else{
	    	 return null;
	     }
}
}
